<template>
  <div class="login-frame">
    <section class="login-cont">
      <h1>财务管理系统</h1>
      <el-form :model="loginRule" :rules="rules" status-icon ref="loginForm" label-width="80px" 
      class="login-ruleForm">
        <el-form-item label="邮箱" prop="email">
          <el-input type="text" placeholder="请输入邮箱" v-model="loginRule.email" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="passWord">
          <el-input type="password" placeholder="请输入密码" v-model="loginRule.passWord"></el-input>
        </el-form-item>
        <el-form-item class="btn-frame">
          <el-button type="primary"
          class="login-btn"
          @click="submitForm('loginForm')">登录</el-button>
        </el-form-item>
          <p style="text-align:right">没有账号？<router-link to="/register">去注册</router-link></p>
      </el-form>
    </section>
  </div>
</template>

<script>
import jwt_decode from "jwt-decode"
export default {
  name:"Login",
  data() {
      return {
        loginRule: {
          passWord:"",
          email:""
        },
        rules:{
          passWord:{
            required:true,
            message:"密码不能为空"
          },
          email:{
            required:true,
            message:"邮箱不能为空"
          }
        }
      };
    },
    methods: {
      submitForm(formName){
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.$axios.post("/api/user/login",this.loginRule).then(res=>{
              const token=res.data.token;
              //存到 localstorage 
              localStorage.setItem("eletoken",token);
              //解析token 
              const decode = jwt_decode(token);
              console.log(localStorage.getItem("eletoken"))
              this.$store.dispatch("setAuthenticated",!this.isEmpty(decode));
              this.$store.dispatch("setUser",decode);
              this.$router.push({path:"/main"});
            })
          } else {
            return false;
          }
        });
      },
      isEmpty(value){
        return (
          value === undefined || 
          value === null ||
          ( typeof value ==="object" && Object.keys(value).length===0)||
          ( typeof value ==="string" && value.trim().length===0)
        );
      }
    }
}
</script>

<style scoped>
.login-frame{
  width: 100%;
  height: 100%;
  background: url("../assets/bg.jpg") center no-repeat;
  background-size: 100%;
  padding-top: 3rem;
  box-sizing: border-box;
}
.login-cont{
  margin:0 auto;
  
  width: 8rem;
}
.btn-frame{
  text-align: center;
}
.login-cont h1{
  margin-bottom: 0.4rem;
  font-size: 0.7rem;
  color: #fff;
  font-weight: 600;
  text-align: center;
  font-family: 'Courier New', Courier, monospace;
}
.login-ruleForm{
  background: #fff;
  margin: 0 auto;
  padding: 0.8rem 0.8rem  0.8rem 0rem;
  border: 0.02rem solid #ccc;
  border-radius: 0.2rem;
  box-shadow: 0rem 0 0.8rem #ccc;
}
.login-btn{
  text-align: center;
  width: 100%;
}
</style>
